package com.sd.chat;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientMain extends Thread {

    //private ChatClientView clientView;
    //private String serverAddress = "127.0.0.1";
    //private int serverPort = 7676;
    private ClientManager manager;
    private ConnectionHandler con;
    private boolean shutdown = false;

    public ClientMain(String name) {
        super(name);
    }

    public ClientMain(String name, ChatClientView clientView) {
        super(name);
        //this.clientView = clientView;
        startUp(clientView);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("run() ClientMain");
        manager.start();
        while (!shutdown) {
            if (!manager.isAlive()) {
                break;
            }

            manager.dispatchToGUI();
        }
        System.out.println("ClientMain going for shutdown");
        try {
            manager.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(ClientMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void startUp(ChatClientView clientView) {
        manager = new ClientManager(new ServerData(), clientView);
    }

    private void shutDown() {
        manager.shutdown();
    }

    public boolean isShutdown() {
        return shutdown;
    }

    public synchronized void setShutdown(boolean shutdown) {
        this.shutdown = shutdown;
        if (shutdown == true) {
            shutDown();
            interrupt();
        }
        notifyAll();

    }

    public ClientManager getManager() {
        return manager;
    }

    public void setManager(ClientManager manager) {
        this.manager = manager;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ClientMain program = new ClientMain("Chat Client");
        program.start();
    }
}
